<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- BIM培训台账 -->
    <div id="base-breadcrumb" style="position: relative; overflow: hidden">
      <!-- 搜索 -->
      <searchData :searchData="searchArr" @search="search"></searchData>
      <!-- 表格 -->
      <a-card :bordered="false">
        <!-- <title-name :title="$route.meta.title"></title-name> -->
        <!-- 表格 -->
        <list-table
          ref="table"
          :pageKeys="['pageNum', 'pageSize', 'total']"
          :columns="columns"
          :startIndex="0"
          :filterData="filterData"
          :request="loadData"
          :statistics-config="{
            use: true, //是否统计，传false不会显示操作栏
            temp: statistics
          }"
          :exportPermission="{ select: 'BIM_005_exp_05', all: 'BIM_005_exp_05' }"
          :exportConfig="{ use: true, select: $route.meta.title, all: $route.meta.title }"
        >
          <!-- 新增 -->
          <a-button
            v-btnPermission="'BIM_005_add_01'"
            slot="prefix"
            class="mb12"
            icon="plus"
            type="primary"
            @click="handleManage(2)"
            >新增</a-button
          >
          <!-- 下载附件 -->
          <template slot="suffix" slot-scope="scoped">
            <a-button
              v-btnPermission="'BIM_005_dow_06'"
              :loading="downLoading"
              class="mb12"
              icon="cloud-download"
              :disabled="scoped.selectedRowKeys && scoped.selectedRowKeys.length === 0"
              type="primary"
              @click="downZip(scoped.selectedRowsMap)"
              >批量下载附件</a-button
            >
            <ExportExcel
              ref="exportExcel"
              :export-list="exportList"
              icon="export"
              :file-name="$route.meta.title + '模板.xlsx'"
              button-text="下载导入模板"
              :beforeDownload="beforeDownload"
            />
            <ExcelImportButton
              ref="excelImportButton"
              :loading="loadingImport"
              icon="import"
              button-text="批量导入"
              @handleSubmit="handleImport"
              v-if="hideBuquBtn()"
            />
          </template>
          <template slot="actions" slot-scope="text, record">
            <MoreButton>
              <template v-if="record.fileInfoList && record.fileInfoList.length > 0">
                <a
                  v-btnPermission="'BIM_005_loo_02'"
                  @click="
                    fileList = record.fileInfoList
                    visible = true
                  "
                  >查看附件({{ record.fileInfoList ? record.fileInfoList.length : 0 }})</a
                >
                <!-- <a v-btnPermission="'BIM_005_loo_02'" @click="handleManage(0, record)">查看</a> -->
                <a-divider v-btnPermission="'BIM_005_loo_02'" type="vertical"></a-divider>
              </template>
              <a v-btnPermission="'BIM_005_edi_03'" @click="handleManage(1, record)">编辑</a>
              <template>
                <a-divider v-btnPermission="'BIM_005_del_04'" type="vertical"></a-divider>
                <a v-btnPermission="'BIM_005_del_04'" class="del_btn" @click="handleRemove(record.id, search)">删除</a>
              </template>
            </MoreButton>
          </template>
        </list-table>
      </a-card>
    </div>
    <!-- 查看附件 -->
    <DialogForm ref="dialogForm" :visible.sync="visible" edit-model="V" :width="1000" :fileList="fileList" />
    <ExportResult :visible.sync="visibleExport" :exportList="exportList" width="80%" />
  </base-breadcrumb>
</template>

<script>
import {
  getPageBimTrainLedger,
  deleteBimTrain,
  getBimTrainLedgerSummary,
  insertBimTrainBatch,
  getPageTypesLabel
} from '@/api/bimIntegrate/bimResource.js'
import BasePage from '@/views/basePage'
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject'
import DialogForm from '@/components/DialogForm' // 弹窗
import ExportExcel from '@/components/exportExcel/ExportExcel' // 导出
import ExportResult from '@/components/Dialog/ExportResult' // 弹窗
import Selector from '@/components/Select/Selector'
import OrgTreeSelect from '@/components/OrgTreeSelect'

const searchArr = [
  // 搜索框
  {
    name: '培训类别',
    type: 'select',
    value: 'category',
    data: [
      {
        label: '信息化',
        value: 0
      },
      {
        label: 'BIM',
        value: 1
      }
    ]
  },
  {
    name: '单位',
    valueKey: 'searchQuery',
    type: OrgTreeSelect,
  },
  // {
  //   name: '单位',
  //   valueKey: 'unitId',
  //   type: SelectCompanyAndProject,
  //   extraParams: {
  //     notContainTags: ['PD']
  //   }
  // },
  {
    name: '培训内容',
    valueKey: 'trainContentId',
    type: Selector,
    customApi: getPageTypesLabel,
    customQuery: { param: { type: '39' } },
    dataValue: 'data.list'
  },
  {
    name: '组织方',
    valueKey: 'organizerId',
    type: SelectCompanyAndProject,
    extraParams: {
      notContainTags: ['PD']
    }
  },
  {
    name: '培训时间',
    type: 'dateRange',
    value: 'trainTime',
    attr: {
      rangeFormat: ['startTime', 'endTime']
    }
  }
]
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    isHidden: true,
    width: 80,
    customRender() {
      return Number(arguments[2]) + 1
    }
  },
  {
    title: '单位',
    ellipsis: true,
    dataIndex: 'unitName'
  },
  {
    title: '培训时间',
    ellipsis: true,
    width: 190,
    dataIndex: 'trainTime',
    customRender() {
      return arguments[1].startDate && arguments[1].endDate ? arguments[1].startDate + '~' + arguments[1].endDate : '无'
    },
    excelConfig: {
      note: '日期格式：XXXX年XX月XX日-XXXX年XX月XX日；如：2020年10月1日-2020年10月4日'
    }
  },
  {
    title: '培训内容',
    ellipsis: true,
    dataIndex: 'trainContent'
  },
  {
    title: '培训类别',
    ellipsis: true,
    dataIndex: 'categoryName',
    excelConfig: {
      dataValidation: {
        type: 'list'
      }
    },
    options: ['信息化', 'BIM']
  },
  {
    title: '组织方',
    ellipsis: true,
    dataIndex: 'organizer'
  },
  {
    title: '授课人',
    ellipsis: true,
    dataIndex: 'lecturer'
  },
  {
    title: '培训人数',
    ellipsis: true,
    dataIndex: 'numberOfPeople',
    minWidth: '80px',
  },
  {
    title: '总学时',
    ellipsis: true,
    dataIndex: 'totalClasshours',
    minWidth: '80px',
  },
  {
    title: '人均学时',
    ellipsis: true,
    dataIndex: 'averageClasshours',
    minWidth: '80px',
  },
  {
    title: '培训地点',
    ellipsis: true,
    dataIndex: 'placeForTraining'
  },
  {
    title: '培训形式',
    ellipsis: true,
    dataIndex: 'trainingForm'
  },
  {
    title: '更新时间',
    width: 180,
    isHidden: true,
    ellipsis: true,
    dataIndex: 'modifiedTime'
  },
  {
    title: '操作',
    dataIndex: 'actions',
    width: '230px',
    isHidden: true,
    align: 'center',
    fixed: 'right',
    scopedSlots: { customRender: 'actions' }
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BasePage(),
  components: {
    DialogForm,
    ExportResult,
    ExportExcel
  },
  data() {
    this.columns = columns
    this.searchArr = searchArr
    return {
      queryParam: {}, // 查询参数
      removeApi: { remove: deleteBimTrain }, // 删除台账
      visible: false, // 查看附件弹窗控件
      visibleExport: false, // 导入结果弹窗控件
      exportList: [{ columns: [], datas: [] }], // 导入配置项
      fileList: [], // 当前文件列表
      loadingImport: false, // 导入loading
      countInfo: {}, // 汇总数据
      countList: [
        {
          name: '信息化',
          list: [
            {
              title: '培训总数：',
              value: 'infoTotal',
              unit: '人'
            },
            {
              title: '总人次：',
              value: 'infoPeople',
              unit: '人次'
            }
          ]
        },
        {
          name: 'BIM',
          list: [
            {
              title: '培训总数：',
              value: 'bimTotal',
              unit: '人'
            },
            {
              title: '总人次：',
              value: 'bimPeople',
              unit: '人次'
            }
          ]
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        this.getSummary()
        const requestParameters = Object.assign({}, parameter, { param: this.queryParam })
        return getPageBimTrainLedger(requestParameters).then((res) => {
          if (res.code === '0') {
            return { code: 200, data: res.data?.list, total: res.data?.total }
          }
        })
      },
      importCheck: {
        单位: 'unitName',
        培训时间: 'trainTime',
        培训内容: 'trainContent',
        培训类别: 'categoryName',
        组织方: 'organizer',
        授课人: 'lecturer',
        培训人数: 'numberOfPeople',
        总学时: 'totalClasshours',
        人均学时: 'averageClasshours',
        培训地点: 'placeForTraining',
        培训形式: 'trainingForm'
      } // 导入字段对应
    }
  },
  methods: {
    /**
     * @description: 导出模板前的回调处理
     * @param {Promise} callback：导出方法
     */
    async beforeDownload() {
      let columnsExport = this.$clone(this.columns)
      // 若培训内容枚举值不存在，则添加培训内容的枚举值
      if (!columnsExport[3].options) {
        this.loadingExport = true
        const res = await getPageTypesLabel({ param: { type: '39' } }).catch(() => {
          this.loadingExport = false
        })
        if (res?.code === '0') {
          // 添加培训内容枚举
          columnsExport[3].options = res.data?.list?.map((item) => item.name)
        }
      }
      // 设置默认导出配置项
      this.exportList = [
        {
          columns: columnsExport,
          datas: [{}]
        }
      ]
    },
    /**
     * @description: 批量导入
     * @param {Array} data：导入列表
     */
    async handleImport(e) {
      let form = []
      // 遍历校验表格字段，且添加表单
      for (let index in e) {
        form.push({})
        let keys = e[index]
        let listItem = form[index]
        // 校验excel的表头字段
        for (let i in this.importCheck) {
          let item = this.importCheck[i]
          if (!Object.keys(keys).includes(i) && item !== 'remark') {
            this.$message.warning(`第${Number(index) + 1}行${i}不能为空`)
            return
          } else {
            // 培训类别格式化
            if (item === 'categoryName') {
              listItem[item] = keys[i]
              listItem['category'] = { 信息化: 0, BIM: 1 }[keys[i]]
              // 培训人数/总学时/人均学时：校验数字类型
            } else if (
              (item === 'numberOfPeople' || item === 'totalClasshours' || item === 'averageClasshours') &&
              typeof keys[i] !== 'number'
            ) {
              this.$message.warning(`第${Number(index) + 1}行${i}必须为数字`)
              return
            } else if (item === 'trainTime') {
              let trainTime = keys[i]?.split('-')
              let isDate = /年|月|日/g
              let formatDate = (e) => {
                return e?.replace(/年|月/g, '-')?.replace(/日/g, '')
              }
              if (trainTime.length === 2 && isDate.test(trainTime[0]) && isDate.test(trainTime[1])) {
                // 添加培训开始时间
                listItem.startDate = formatDate(trainTime[0])
                // 添加培训结束时间
                listItem.endDate = formatDate(trainTime[1])
              } else {
                this.$message.warning(
                  `第${Number(index) + 1}行${i}格式不正确，请填写成类似如"2020年10月1日-2020年10月4日"格式`
                )
                return
              }
            } else {
              listItem[item] = keys[i]
            }
          }
        }
      }
      // 开始导入
      this.loadingImport = true
      const importRes = await insertBimTrainBatch(form).catch(() => {
        this.loadingImport = false
      })
      this.loadingImport = false
      // 导入成功
      if (importRes?.code === '0') {
        if (importRes.data?.list?.length > 0) {
          // 配置导出项，且打开导出结果
          let columnsExport = this.$clone(this.columns)?.filter((i) => i.header !== '操作' && !i.isHidden)
          // 若培训内容枚举值不存在，则添加培训内容的枚举值
          if (!columnsExport[2].options) {
            this.loadingImport = true
            const ress = await getPageTypesLabel({ param: { type: '39' } }).catch(() => {
              this.loadingImport = false
            })
            this.loadingImport = false
            // 添加下拉枚举值
            if (ress?.code === '0') {
              // 添加培训内容枚举
              columnsExport[2].options = ress.data?.list?.map((item) => item.name)
            }
          }
          // 表头添加失败原因
          columnsExport.push({
            dataIndex: 'failureReason',
            ellipsis: true,
            title: '失败原因'
          })

          this.exportList = [
            {
              successCount: importRes.data.successCount,
              columns: columnsExport,
              datas: importRes.data.list
            }
          ]
          this.visibleExport = true
        } else {
          this.$message.success('导入成功')
        }
        // 如果有导入成功条数，则刷新表格
        importRes.data?.successCount > 0 && this.search()
      }
    },
    /**
     * 汇总请求
     */
    getSummary() {
      getBimTrainLedgerSummary({ param: this.queryParam }).then((res) => {
        if (res.code === '0') {
          this.countInfo = res.data
        }
      })
    },
    /**
     * 汇总
     */
    statistics() {
      return this.countList.map((item, index) => (
        <span key={index}>
          <a>
            <b>【{item.name}】</b>
          </a>
          {item.list.map((i, idx) => (
            <span key={idx}>
              {i.title}
              <a>
                <b>{this.countInfo?.[i.value] || 0 + i.unit}</b>
              </a>
              {idx % 2 === 0 ? '，' : ''}
            </span>
          ))}
          {index == 0 && (
            <span style="padding:0 12px;position:relative">
              <span style="width:2px;height:100%;color:#40a9ff;position:absolute;top:-2px;font-weight:bolder">|</span>
            </span>
          )}
        </span>
      ))
    },
    /**
     * 格式话数据
     */
    filterData(datas) {
      let list = this.$clone(datas)
      list.forEach((item, index) => {
        item.index = index + 1
        item.category = ['信息化', 'BIM'][item.category]
        item.trainTime = item.startDate && item.endDate ? item.startDate + '~' + item.endDate : '无'
      })
      return list
    },
    /**
     * 搜索
     */
    search(value) {
      value && (this.queryParam = value)
      this.$refs.table.getData(null, true)
    },
    /**
     * 操作栏
     */
    handleManage(type, record) {
      this.editModel = type
      let query = {
        editModel: type
      }
      if (record && record.id) {
        query.id = record.id
      }
      this.$router.push({
        name: '/bimResource/trainingLedgerEdit',
        query
      })
    }
  }
}
</script>
